package com.community.windy.controller;

import com.community.windy.annotion.LoginRequired;
import com.community.windy.entity.User;
import com.community.windy.service.FollowService;
import com.community.windy.service.LikeService;
import com.community.windy.service.UserService;
import com.community.windy.util.CommunityConstant;
import com.community.windy.util.CommunityUtil;
import com.community.windy.util.HostHolder;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;


@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger= LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private FollowService followService;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(){
        return "/site/setting";
    }

    @LoginRequired
    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model){
        if (headerImage==null){
            model.addAttribute("error","您好没有选择图片");
            return "/site/setting";
        }
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式不正确");
            return "/site/setting";
        }
        //生成随机文件名
        fileName = CommunityUtil.generateUUID()+suffix;
        //确定文件存放的路径
        File dest = new File(uploadPath+"/"+fileName);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
           logger.error("上传文件失败"+e.getMessage());
           throw new RuntimeException("上传文件失败，服务器发现异常",e);
        }
        //更新当前用户头像的路径（web路径）
        User user = hostHolder.getUser();
        String headerUrl = domain+contextPath+"/user/header/"+fileName;
        userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }

    /**
     * 获取头像
     * @param fileName 文件名
     * @param response
     */
    @GetMapping("/header/{fileName}")
    public void  getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        //服务器存放路径
        fileName =  uploadPath +"/"+fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        //响应图片
        response.setContentType("image/"+suffix);
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(fileName);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int b=0;
            while ((b= fis.read(buffer))!= -1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败："+e.getMessage());
        }finally {
            if (fis!=null){
                fis.close();
            }
            if (os!=null){
                os.close();
            }
        }
    }

    @PostMapping(path = "/updatePassword")
    @LoginRequired
    public String updatePassword(String originPassword,String newPassword,String repeatPassword,Model model){
        // 获取当前登录用户信息
        User user = hostHolder.getUser();
        model.addAttribute("originPassword",originPassword);
        model.addAttribute("newPassword",newPassword);
        model.addAttribute("repeatPassword",repeatPassword);

        // 密码信息校验
        if(!CommunityUtil.md5(originPassword).equals(user.getPassword())){
            model.addAttribute("errorMsg1","原密码错误");
            return "site/setting";
        }

        if(CommunityUtil.md5(newPassword).equals(user.getPassword())){
            model.addAttribute("errorMsg2","新密码不能与原密码一样");
            return "site/setting";
        }

        if(!newPassword.equals(repeatPassword)){
            model.addAttribute("errorMsg3","两次输入密码不一致");
            return "site/setting";
        }

        user.setPassword(CommunityUtil.md5(newPassword));
        int result = userService.updatePassword(user);
        if(result<=0){
            model.addAttribute("errorMsg","更新密码失败");
            return "site/setting";
        }

        return "redirect:/index";
    }

    //个人主页
    @GetMapping(path = "/profile/{userId}")
    public String getProfilePage(@PathVariable("userId")int userId,Model model){
        User user = userService.findUserById(userId);
        if (user==null){
            throw  new RuntimeException("用户不存在");
        }
        //用户
        model.addAttribute("user",user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if(hostHolder.getUser() !=null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);

        model.addAttribute("likeCount",likeCount);
        return "/site/profile";
    }

}
